package com.xxxx.myproject.exception;

import com.xxxx.myproject.entity.R;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;


@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public R<String> ExceptionHandler(Exception e){
        if(e instanceof GlobalException){
            GlobalException ex = (GlobalException) e;
            return R.fail(ex.getMessage());
        }else if(e instanceof BindException){
            BindException ex = (BindException) e;
            System.out.println(ex);
            List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
            StringBuilder stringBuilder = new StringBuilder();
            for (ObjectError error:allErrors) {
                stringBuilder.append(error.getDefaultMessage());
                stringBuilder.append(",");
            }
            String fault = stringBuilder.toString();
            String substring = fault.substring(0, fault.length() - 1);
            return R.fail("参数校验异常: " + substring);
        }
        return R.fail("系统异常");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public R<Void> handleRuntimeException(RuntimeException e) {
        System.out.println("运行时异常");
        System.out.println(e.getMessage());
        return R.fail(e.getMessage());
    }
}
